/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.feature.dubbo;

import jakarta.annotation.Resource;
import org.apache.dubbo.config.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

//@DubboComponentScan(basePackages = "xxx.xxx")
@EnableConfigurationProperties(YhaoDubboProperties.class)
public class DubboConfig {
    @Resource
    private Environment env;

    @Bean
    public ApplicationConfig applicationConfig(YhaoDubboProperties properties) {
        ApplicationConfig config = new ApplicationConfig();
        config.setOrganization(properties.getApplicationOrg());
        config.setOwner(properties.getApplicationOwner());
        config.setName(properties.getApplicationName());
        config.setLogger("slf4j");
        return config;
    }

    @Bean
    public RegistryConfig registryConfig(YhaoDubboProperties properties) {
        RegistryConfig config = new RegistryConfig();
        //使用注册中心暴露服务地址
        config.setProtocol(properties.getRegistryProtocol());
        config.setAddress(properties.getRegistryAddress());
        config.setTimeout(properties.getRegistryTimeout());
        config.setFile(env.getProperty("user.home")
                +"/dubbo-registry/dubbo-registry-"
                +properties.getApplicationName()+"-"
                +properties.getApplicationOwner()+"-"
                +properties.getApplicationName()+".cache");
        return config;
    }

    @Bean
    public ProtocolConfig protocolConfig(YhaoDubboProperties properties) {
        ProtocolConfig config = new ProtocolConfig();
        config.setName("dubbo");
        config.setPort(properties.getProtocolPort());
        return config;
    }

    @Bean
    public MonitorConfig monitorConfig() {
        MonitorConfig config = new MonitorConfig();
        //监控中心配置，protocol="registry"，表示从注册中心发现监控中心地址
        config.setProtocol("registry");
        return config;
    }

    @Bean
    public ConsumerConfig consumerConfig(YhaoDubboProperties properties) {
        ConsumerConfig config = new ConsumerConfig();
        config.setCheck(properties.isConsumerCheck());
        config.setTimeout(properties.getConsumerTimeout());
        return config;
    }
}
